﻿// SerializationHelperLib
// (c)2007 Mark Bulmahn. mBulmahn@web.de
// License: GPL 2.0
// Project: TestCaseGenerator. http://www.codeplex.com/TestCaseGenerator

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace SerializationHelperLib
{
    /// <summary>
    /// Generic base class for xml persistable classes
    /// </summary>
    /// <typeparam name="T">Type to be persisted</typeparam>
    public class XmlPersistenceBase<T>
    {
        /// <summary>
        /// Save an instance as an XML file
        /// </summary>
        /// <param name="fn">Filename</param>
        public void SaveAsXml(string fn)
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextWriter tw = new StreamWriter(fn))
            {
                ser.Serialize(tw, this);
            }
        }

        /// <summary>
        /// Create a new instance from a persisted xml file
        /// </summary>
        /// <param name="fn"></param>
        /// <returns></returns>
        public static T CreateFromXml(string fn)
        {
            T o = default(T);
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextReader tr = new StreamReader(fn))
            {
                o = (T)ser.Deserialize(tr);
            }
            return o;
        }
    }
}
